package com.profgj.profgj.controlleradvice;

import com.profgj.profgj.enums.ServerStatus;
import com.profgj.profgj.utils.ReturnOperator;
import com.profgj.profgj.vo.ResultMsg;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * 控制层异常捕获(明日改成输出到文件内)
 */
//@RestControllerAdvice(basePackages = {"com.profgj.profgj.controller"})
public class ControllerAdvice {


    /**
     * 异常输出路径
     */
    private String exception_path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "/static/exception";

    /**
     * 取系统当前时间
     */
    private Date date = new Date();

    /**
     * 取得日期时间拼接路径
     * @return
     */
    private String getDateTimePath() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 中间日期路径
        return  "/" + sdf.format(this.date) + "/";
    }

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ResultMsg> errorHandler(Exception ex) {

        // 创建异常日志文件夹(日期)
        File folder = new File(exception_path + getDateTimePath());
        if (!folder.exists()) {
            folder.mkdirs();
        }

        // 构建异常输出文件对象
        File file = new File(exception_path + getDateTimePath() + "exception.txt");
        FileWriter fw = null;
        PrintWriter pw = null;
        try{
            // 创建文件追加输出对象
            fw = new FileWriter(file, true);
            // 支持打印写出到文件的对象
            pw = new PrintWriter(fw);
            // 异常输出到exception.txt文件
            pw.println(ex.getMessage());
            pw.flush();
        }catch (Exception e) {
            e.printStackTrace();
        }

        // 返回web结果
        return ReturnOperator.createResultMsg("", ex.getMessage(), ServerStatus.ERROR,
                new ArrayList<>(), new Object(), HttpStatus.OK);
    }
}